package com.erb.controller.wzq;

import com.erb.common.Constant;
import com.erb.common.FileUpload;
import com.erb.constants.AdminConstants;
import com.erb.constants.AdminProductConstants;
import com.erb.entity.*;
import com.erb.service.ljy.capitalLogService;
import com.erb.service.wzq.AlipayService;
import com.erb.service.wzq.IPersonalService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by MoYao on 2020/6/10.
 */
@Controller
@RequestMapping("/per")
public class PersonalController {

	@Resource
	private IPersonalService ips;

	@Resource
	private capitalLogService logService;

	@Resource
	private AlipayService as;

	//首页
	@RequestMapping("/index")
	public String index(Pager pager, Integer option, Model model, HttpSession session, HttpServletRequest request) {
		User user = (User) session.getAttribute("user");
		user = ips.seluser(user.getId());
		session.setAttribute("user", user);
		//是否有系统消息
		Integer xtsumber = ips.countinf(user.getId(), 0);  //0为未读，1为已读。
		if (xtsumber > 0) {
			model.addAttribute("xx", 1);
		} else if (xtsumber == 0) {
			model.addAttribute("xx", 0);
		}
		//查询是否进行了第三方支付认证
		Thirdparty thi = ips.selthi(user.getId());
		if (thi == null) {  //未进行第三方支付认证时
			model.addAttribute("thi", 0);
		} else {  //已认证
			model.addAttribute("thi", 1);
		}
		//判断条件一（投资记录总条数）
		Integer tzsumber = ips.selinvest(user.getId());
		if (user.getBalance() == 0 && tzsumber == 0) {
			model.addAttribute("userstatus", 1);  //无账户总额（无余额+无待收本息）、无待收本息、无累计收益（无待收收益+无已收益），账户总额、待收本息、累计收益静态显示。
		} else if (user.getBalance() == 0 && tzsumber > 0) {
			//判断条件二（投资记录中待收收益）
			Integer yssumber = ips.selinvest2(user.getId());
			if (yssumber == 0) {
				model.addAttribute("userstatus", 2);  //无账户总额（无余额+无待收本息）、无待收本息、有累计收益（无待收收益+有已收益），账户总额、待收本息静态显示，累计收益正常显示。
				//累计收益
				Map leijisouyi = ips.investuser2(user.getId());
				model.addAttribute("cumulative_income", leijisouyi);
			} else {
				model.addAttribute("userstatus", 3);  //有账户总额（无余额+有待收本息）、有待收本息、有累计收益（有待收收益+有无已收益都一样），账户总额、待收本息、累计收益正常显示。
				//待收本息
				Map daishoubenxi = ips.investuser(user.getId());
				model.addAttribute("principal_and_interest_to_be_collected", daishoubenxi);
				//账户总额
				model.addAttribute("total_account_amount", daishoubenxi);
				//累计收益
				Map leijisouyi = ips.investuser2(user.getId());
				model.addAttribute("cumulative_income", leijisouyi);
			}
		} else if (user.getBalance() > 0 && tzsumber == 0) {
			model.addAttribute("userstatus", 4);  //有账户总额（有余额+无待收本息）、无待收本息、无累计收益（无待收收益+无已收益），账户总额正常显示，待收本息、累计收益静态显示。
			//账户总额
			model.addAttribute("total_account_amount", user.getBalance());
		} else if (user.getBalance() > 0 && tzsumber > 0) {
			//判断条件二（投资记录中待收收益）
			Integer yssumber = ips.selinvest2(user.getId());
			if (yssumber == 0) {
				model.addAttribute("userstatus", 5);  //有账户总额（有余额+无待收本息）、无待收本息、有累计收益（无待收收益+有已收益），账户总额、累计收益正常显示，待收本息静态显示。
				//账户总额
				model.addAttribute("total_account_amount", user.getBalance());
				//累计收益
				Map leijisouyi = ips.investuser2(user.getId());
				model.addAttribute("cumulative_income", leijisouyi);
			} else {
				model.addAttribute("userstatus", 6);  //有账户总额（有余额+有待收本息）、有待收本息、有累计收益（有待收收益+有无已收益都一样），账户总额、待收本息、累计收益正常显示。
				//待收本息
				Map daishoubenxi = ips.investuser(user.getId());
				model.addAttribute("principal_and_interest_to_be_collected", daishoubenxi);
				//先转换成double父类，然后再转double。（map取值double的规范）
				BigDecimal i1 = (BigDecimal) daishoubenxi.get("i");
				System.out.println("待收本息的值：" + i1.doubleValue());
				double total_balance = user.getBalance() + i1.doubleValue();
				System.out.println("账户总额的值：" + total_balance);
				//账户总额
				model.addAttribute("total_account_amount", total_balance);
				//累计收益
				Map leijisouyi = ips.investuser2(user.getId());
				model.addAttribute("cumulative_income", leijisouyi);
			}
		}
		model.addAttribute("option", option);
		pager.pageSize = 5;
		if (option == 1) {
			Integer i = ips.count2invest(user.getId(), null, "", "");
			pager.page(i);
			model.addAttribute("size", i);
			pager.data = ips.page2invest(pager, user.getId(), null, "", "");
			model.addAttribute("pro", pager);
		} else if (option == 2) {
			Integer j = logService.countselcap(user.getId(), null, "");
			pager.page(j);
			model.addAttribute("size", j);
			pager.data = logService.pageselcap(pager, user.getId(), null, "");
			model.addAttribute("cap", pager);
		} else if (option == 3) {
			Integer k = ips.countinvest(user.getId());
			pager.page(k);
			model.addAttribute("size", k);
			pager.data = ips.pageinvest(pager, user.getId());
			model.addAttribute("inv", pager);
		}
		model.addAttribute("option", option);
		//判断是否为手机登录（java代码判断）
//        String[] mobileAgents = { "iphone", "android","ipad", "phone", "mobile", "wap", "netfront", "java", "opera mobi",
//                "opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry", "dopod",
//                "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma",
//                "docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos",
//                "techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem",
//                "wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos",
//                "pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320",
//                "240x320", "176x220", "w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac",
//                "blaz", "brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs",
//                "kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi",
//                "mot-", "moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port",
//                "prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem",
//                "smal", "smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v",
//                "voda", "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-",
//                "Googlebot-Mobile" };
//        if (request.getHeader("User-Agent") != null) {
//            String agent=request.getHeader("User-Agent");
//            for (String mobileAgent : mobileAgents) {
//                if (agent.toLowerCase().indexOf(mobileAgent) >= 0&&agent.toLowerCase().indexOf("windows nt")<=0 &&agent.toLowerCase().indexOf("macintosh")<=0) {
//                    model.addAttribute("shouji", 1);
//                    break;
//                }else {
//                    model.addAttribute("shouji", 0);
//                }
//            }
//        }
		return "personal/index";
	}

	//更改头像
	@RequestMapping("/upload-headportrait")
	@ResponseBody
	public boolean uploadHeadportrait(@RequestParam("file") MultipartFile file, HttpSession session) {
		User user = (User) session.getAttribute("user");
		String newFileName = FileUpload.uploadAndRename(AdminConstants.ADVERTISEMENT_SAVE_PATH, file);
		boolean bln = ips.updsuser(user.getId(), newFileName);
		if (bln) {
			//头像修改成功后更新session中的user
			user.setFace(newFileName);
			session.setAttribute("user", user);
		}
		return bln;
	}

	//修改用户名
	@ResponseBody
	@RequestMapping("/updname")
	public Integer updname(String name, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer i = ips.updname(user.getId(), name);
		if (i > 0) {  //成功更改用户名
			user.setModificationTime(Constant.THIS_MONTH_CANNOT_BE_MODIFIED);  //本月更改用户名状态改为不可更改该
			//更新session
			user.setName(name);
			session.setAttribute("user", user);
			return 1;
		} else {
			return 0;
		}
	}

	//投资记录
	@RequestMapping("/investlist")
	public String mentlist(Pager pager, Integer option, Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		//判断条件一（投资记录总条数）
		Integer i = ips.selinvest(user.getId());
		if (i == 0) {
			model.addAttribute("zt", 1);  //累计投资、累计收益、待收收益、待收本金静态显示。
		} else if (i > 0) {
			//判断条件二（投资记录中待收收益）
			Integer j = ips.selinvest2(user.getId());
			if (j == 0) {
				//累积投资
				Map zongtouzi = ips.investmentsum(user.getId());
				model.addAttribute("mentsum", zongtouzi);
				//累积收益
				Map leijishouyi = ips.profitsum(user.getId());
				model.addAttribute("revesum", leijishouyi);
				model.addAttribute("zt", 2);  //累计投资、累计收益正常显示，待收本金、待收收益静态显示。
			} else {
				//累积投资
				Map zongtouzi = ips.investmentsum(user.getId());
				model.addAttribute("mentsum", zongtouzi);
				//累积收益
				Map leijishouyi = ips.profitsum(user.getId());
				model.addAttribute("revesum", leijishouyi);
				//待收本息
				Map daishou = ips.investmentssum(user.getId());
				model.addAttribute("menpro", daishou);
				model.addAttribute("zt", 3);  //累计投资、累积收益、待收本金、待收收益正常显示。
			}
		}
		pager.pageSize = 3;
		model.addAttribute("option", option);
		Integer tbcount = ips.countsinvest(user.getId(), option);
		pager.page(tbcount);
		model.addAttribute("size", tbcount);
		pager.data = ips.pagesinvest(pager, user.getId(), option);
		model.addAttribute("invest", pager);
		return "personal/investment_record";
	}

	//删除投资记录，但是投资资金记录不删除(改变投资记录的状态)
	@RequestMapping("/updinvest")
	public String delinvest(int id) {  //投资记录表的id
		ips.updinvest(id);
		return "redirect:investlist";
	}

	//回款计划
	@RequestMapping("/prolist")
	public String prolist(Pager pager, Integer tkey, String date1, String date2, Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		model.addAttribute("typeMap", AdminProductConstants.PRODUCT_TYPE_MAP);  //搜索下拉框选择
		model.addAttribute("tkey", tkey);  //查询后返回页面给下拉框选中
		if ((date1 == "" || date1 == null) && (date2 == "" || date2 == null)) {
			model.addAttribute("sj1", 0);
			model.addAttribute("sj2", 0);
		} else {
			if (date1 != "" && date1 != null) {
				model.addAttribute("sj1", 1);
				model.addAttribute("d1", date1);  //查询后返回页面给开始时间输入框
			} else {
				model.addAttribute("sj1", 0);
			}
			if (date2 != "" && date2 != null) {
				model.addAttribute("sj2", 1);
				model.addAttribute("d2", date2);  //查询后返回页面给结束时间输入框
				date2 = date2 + " 23:59:59";
			} else {
				model.addAttribute("sj2", 0);
			}
		}
		//判断条件一（投资记录总条数）
		Integer i = ips.selinvest(user.getId());
		if (i == 0) {
			model.addAttribute("zt", 1);  //待收本金、待收收益静态显示
		} else if (i > 0) {
			//判断条件二（投资记录中待收收益）
			Integer j = ips.selinvest2(user.getId());
			if (j == 0) {
				model.addAttribute("zt", 2);  //待收本金、待收收益静态显示
			} else {
				Map daishou = ips.investmentssum(user.getId());  //显示待收本金、待收利息
				model.addAttribute("menpro", daishou);
				model.addAttribute("zt", 3);  //待收本金、待收收益正常显示
			}
		}
		//更改每页显示行数
		pager.pageSize = 3;
		//查询总行数
		Integer iner = ips.count2invest(user.getId(), tkey, date1, date2);
		pager.page(iner);
		model.addAttribute("size", iner);
		//把定义的数据传到data，然后直接model发布。【因为data也是pager中的一个属性】
		pager.data = ips.page2invest(pager, user.getId(), tkey, date1, date2);//查询回款项目(连接了项目表和投资记录表)
		model.addAttribute("pro", pager);
		return "personal/collection_plan";
	}

	//去充值页面
	@RequestMapping("/torecharge")
	public String torecharge(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Thirdparty thi = ips.selthi(user.getId());  //查询是否进行了第三方支付认证
		if (thi == null) {
			model.addAttribute("thi", 0);
		} else {
			model.addAttribute("thi", 1);
			List<Bankcard> list = ips.listban(user.getId());  //查询银行卡
			if (list.size() == 0) {
				model.addAttribute("ban", null);
			} else {
				for (Bankcard ba : list) {
					String bank = ba.getBankn().substring(0, 4) + "****" + ba.getBankn().substring(15, 19);
					ba.setBankn(bank);
				}
				model.addAttribute("ban", list);
			}
		}
		return "personal/recharge";
	}

	//跳转去第三方支付绑定
	@RequestMapping("/thirdparty")
	public String thirdparty(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		String phone = user.getPhone();
		phone = phone.substring(0, 3) + "****" + phone.substring(7, 11);
		model.addAttribute("phone", phone);
		String email = user.getEmail();
		email = email.replaceAll("(\\w?)(\\w+)(\\w)(@\\w+\\.[a-z]+(\\.[a-z]+)?)", "$1****$3$4");
		model.addAttribute("email", email);
		Thirdparty thi = ips.selthi(user.getId());
		model.addAttribute("thi", thi);
		return "personal/open_third_party";
	}

	//实名
	@RequestMapping("/addidentitycard")
	public String addidentitycard(Thirdparty thirdparty) {
		ips.addthi(thirdparty);
		Integer i = Integer.parseInt(thirdparty.getIdentitycard().substring(16, 17));
		if (i % 2 == 0) {  //偶数，为女性
			String sex = "女";
			ips.updusers(thirdparty.getUid(), sex);
		} else if (i % 2 != 0) {  //奇数，为男性
			String sex = "男";
			ips.updusers(thirdparty.getUid(), sex);
		}
		return "personal/open_third_party2";
	}

	//银行卡充值到余额
	@RequestMapping("/payment")
	@ResponseBody
	public Integer payment(Integer pwd, double amount, CapitalLog capitalLog, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Thirdparty thi = ips.selthis(user.getId(), pwd);
		if (thi == null) {
			return 0;
		} else {
			//实时查询用户余额
			User user1 = ips.seluser(user.getId());
			capitalLog.setTradeMoney(amount);  //充值金额
			amount = amount + user1.getBalance();  //余额加上充值金额
			ips.upduser(user.getId(), amount);  //存入用户余额中
			capitalLog.setUid(user.getId());  //用户id
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			capitalLog.setTradeDate(sdf.format(new Date()));  //交易时间
			capitalLog.setType(Constant.TRANSFER_IN_BALANCE);  //交易类型：充值到余额
			capitalLog.setRemark("银行卡充值");  //备注
			ips.addcap(capitalLog);  //存入资金记录表中
			//更新session
			user.setBalance(amount);
			session.setAttribute("user", user);
			return 1;
		}
	}

	//添加银行卡
	@RequestMapping("/addbankcard")
	@ResponseBody
	public Boolean addbankcard(Bankcard bankcard, HttpSession session) {
		User user = (User) session.getAttribute("user");
		bankcard.setUid(user.getId());
		Boolean bln = ips.addban(bankcard);
		return bln;
	}

	//调用支付宝沙箱支付
	@RequestMapping("/pay")
	public void pay(HttpServletResponse response, double amount) {
		try {
			as.aliPay(response, amount);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//异步或同步请求支付宝沙箱支付后返回的参数
	@RequestMapping("/parameters")
	public String parameters(double total_amount, CapitalLog capitalLog, HttpSession session) {
		User user = (User) session.getAttribute("user");
		//实时查询用户余额
		User user1 = ips.seluser(user.getId());
		capitalLog.setTradeMoney(total_amount);  //充值金额
		total_amount = total_amount + user1.getBalance();  //余额加上充值金额
		ips.upduser(user.getId(), total_amount);  //存入用户余额中
		capitalLog.setUid(user.getId());  //用户id
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		capitalLog.setTradeDate(sdf.format(new Date()));  //交易时间
		capitalLog.setType(Constant.TRANSFER_IN_BALANCE);  //交易类型：充值到余额
		capitalLog.setRemark("支付宝沙箱充值");  //备注
		ips.addcap(capitalLog);  //存入资金记录表中
		//更新session
		user.setBalance(total_amount);
		session.setAttribute("user", user);
		return "redirect:torecharge";
	}

	//去提现页面
	@RequestMapping("/towithdrawal")
	public String towithdrawal(Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Thirdparty thi = ips.selthi(user.getId());  //查询是否进行了第三方支付认证
		User user2 = ips.seluser(user.getId());  //用于实时更新用户信息
		model.addAttribute("user", user2);
		if (thi == null) {  //未进行第三方支付认证时
			model.addAttribute("thi", 0);
		} else {  //已认证
			model.addAttribute("thi", 1);
		}
		return "personal/withdrawal";
	}

	//提现
	@RequestMapping("/withdrawal")
	@ResponseBody
	public Integer withdrawal(Integer pwd, double amount, CapitalLog capitalLog, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Thirdparty thi = ips.selthis(user.getId(), pwd);
		if (thi == null) {
			return 0;
		} else {
			//实时查询用户余额
			User user1 = ips.seluser(user.getId());
			capitalLog.setTradeMoney(0 - amount);  //提现金额
			amount = user1.getBalance() - amount;  //余额减去提现金额
			ips.upduser(user.getId(), amount);  //存入用户余额中
			capitalLog.setUid(user.getId());  //用户id
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			capitalLog.setTradeDate(sdf.format(new Date()));  //交易时间
			capitalLog.setType(Constant.TRANSFER_OUT_OF_BALANCE);  //交易类型：余额提现
			capitalLog.setRemark("余额提现");  //备注
			ips.addcap(capitalLog);  //存入资金记录表中
			//更新session
			user.setBalance(amount);
			session.setAttribute("user", user);
			return 1;
		}
	}

	//去我的红包
	@RequestMapping("/toredenvelopes")
	public String toredenvelopes(Pager pager, Integer state, Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		model.addAttribute("state", state);  //标记
		pager.pageSize = 2;
		Integer i = ips.countredp(user.getId(), state);
		pager.page(i);
		model.addAttribute("size", i);
		//把定义的数据传到data，然后直接model发布。【因为data也是pager中的一个属性】
		pager.data = ips.pageredp(pager, user.getId(), state);
		model.addAttribute("redp", pager);
		return "personal/my_red_bag";
	}

	//兑换码兑换红包
	@RequestMapping("/selredenvelopes")
	@ResponseBody
	public Integer selredenvelopes(String exchangeCode, HttpSession session, Redpacketrecord redpd) {
		User user = (User) session.getAttribute("user");
		//首先查询此兑换码是否正确
		Redenvelopes red = ips.selred(exchangeCode);
		if (red == null) {  //兑换码不存在时
			return 0;
		} else {  //兑换码存在时
			//验证是此兑换码否过期
			if (red.getState() == 2) {  //过期了
				return 1;
			} else if (red.getState() == 1) {
				//验证是否已经领取过了
				Redpacketrecord redp = ips.selredp(user.getId(), exchangeCode);
				if (redp != null) {  //已领取过了
					return 2;
				} else {  //未领取过
					redpd.setUid(user.getId());
					redpd.setName(red.getRname());
					redpd.setDescribe(red.getDescribe());
					redpd.setExchangeCode(red.getExchangeCode());
					redpd.setAmount(red.getAmount());
					redpd.setRtype(red.getRtype());
					redpd.setThreshold(red.getThreshold());
					redpd.setPtype(red.getRtype());
					//时间转换
					String datered = ips.datered(exchangeCode);
					redpd.setDeadline(datered);
					redpd.setExchangeTime("");  //兑换时间
					redpd.setState(1);
					ips.addredp(redpd);
					return 3;
				}
			}
		}
		return 0;
	}


	//去系统消息
	@RequestMapping("/tomessages")
	public String tomessages(Pager pager, Integer readed, Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		model.addAttribute("rea", readed);  //返回页面做标记
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		pager.pageSize = 4;
		Integer i = ips.countinf(user.getId(), readed);
		pager.page(i);
		model.addAttribute("size", i);
		List<Inform> list = ips.pageinf(pager, user.getId(), readed);
		Map<Integer, String> map = new HashMap<>(list.size());
		for (Inform in : list) {  //把数据库中的毫秒数转换为"yyyy-MM-dd HH:mm:ss"格式。
			in.setInformContent(in.getInformContent().substring(0, 16) + "...");
			map.put(in.getInformId(), sdf.format(new Date(in.getSendTime())));  //数据格式为{3=2020-06-28 11:20:41}：{id=时间}
		}
		pager.data = list;
		model.addAttribute("inform", pager);
		model.addAttribute("datetimeMap", map);
		return "personal/system_messages";
	}

	//查看通知详情
	@RequestMapping("/todetails")
	public String todetails(Integer id, Integer currPage, Integer readed, Model model, HttpSession session) {
		User user = (User) session.getAttribute("user");
		model.addAttribute("rea", readed);  //返回页面做标记
		model.addAttribute("currPage", currPage);  //返回页面做标记
		Inform inform = ips.selinfr(id, user.getId());
		if (!inform.isReaded()) {  //true为已读，false为未读。
			ips.updinf(inform.getInformId(), true);  //把点击查看的设置为已读
		}
		model.addAttribute("inform", inform);
		return "personal/system_messages_details";
	}
}
